package com.wanshi.servlet;

import com.wanshi.entity.User;
import com.wanshi.service.UserService;
import com.wanshi.utils.MD5Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class login extends HttpServlet {

	UserService userService = new UserService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//1 获取用户名  面
		String username = request.getParameter("username");
		String password =  MD5Utils.md5(request.getParameter("password"));
		
		//2  判断是否存在

		User user = userService.finUserByNameAndPsd(username,password);
		
		//3
		if(user == null){
			request.setAttribute("error", "用户名或密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}else{
			if(user.getState() == 0){
				request.setAttribute("error", "该用户尚未激活");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}else{
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				Cookie cookie = new Cookie("JSESSIONID",session.getId());
				cookie.setPath(request.getContextPath());
				cookie.setMaxAge(1800);
				response.addCookie(cookie);
				response.sendRedirect(request.getContextPath()+"/index.jsp");
			}
			
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}